class_name ActionPick
extends Node

var enemy:Enemy:set=_setEnemy

var target:Node2D:set=_setTarget

@onready var totalWeight:=0.0


func _ready()->void:
	target=get_tree().get_first_node_in_group('player')
	initOrder()

# 初始化行动的顺序
func initOrder()->void:
	var action:Action
	for child in get_children():
		action=child
		if !action or action.type==Action.Type.CONDITION:continue
		totalWeight+=action.weight
		action.sumWeight=totalWeight
		
 
# 获取当前行动
func getAction()->Action:
	var action:=getConditionAction()
	if action:return action
	return getBaseAction()

# 获取一个条件行动
func getConditionAction()->Action:
	var action:Action
	for child in get_children():
		action=child
		if !action or action.type!=Action.Type.CONDITION:continue
		if action.isPerform():return action
	return null

# 获取一个基础行动
func getBaseAction()->Action:
	var action:Action
	var roll:=randf_range(0.0,totalWeight)
	for child in get_children():
		action=child
		if !action or action.type!=Action.Type.BASE:continue
		if action.sumWeight>roll:return action
	return null

func _setEnemy(val:Enemy)->void:
	enemy=val
	for action in get_children():
		action.enemy=enemy
		
func _setTarget(val:Node2D)->void:
	target=val
	for action in get_children():
		action.target=target